﻿namespace ThreeByte.ActiveDeck.Dashboard
{
    using System.Windows.Controls;
    using System.Windows.Navigation;
    using ThreeByte.ActiveDeck.Web;
using System.ServiceModel.DomainServices.Client;

    /// <summary>
    /// Home page for the application.
    /// </summary>
    public partial class Billing : Page
    {
        /// <summary>
        /// Creates a new <see cref="Home"/> instance.
        /// </summary>
        public Billing() {
            InitializeComponent();

        }

        private static readonly string PRESENTER_ROLE = @"Presenter";

        /// <summary>
        /// Executes when the user navigates to this page.
        /// </summary>
        protected override void OnNavigatedTo(NavigationEventArgs e) {
            WebContext.Current.Authentication.LoadUser();

            PresenterCheckBox.IsChecked = WebContext.Current.User.IsInRole(PRESENTER_ROLE);
            PresenterCheckBox.Checked += new System.Windows.RoutedEventHandler(PresenterChecked);
            PresenterCheckBox.Unchecked += new System.Windows.RoutedEventHandler(PresenterUnchecked);

            _dashboardContext.IsEmailVerified(EmailVerified_Complete, null);
        }

        private DashboardAccessContext _dashboardContext = new DashboardAccessContext();

        private void EmailVerified_Complete(InvokeOperation<bool> op) {
            if(!(op.HasError) && op.Value) {
                PresenterCheckBox.IsEnabled = true;
            } else {
                VerifyEmailNotice.Visibility = System.Windows.Visibility.Visible;
            }
        }

        private UserRegistrationContext _ctx = new UserRegistrationContext();

        private void PresenterChecked(object sender, System.Windows.RoutedEventArgs e) {
            SavingIndicator.IsBusy = true;
            _ctx.AddUserRole(PRESENTER_ROLE, OperationComplete, null);
            WebContext.Current.Authentication.LoadUser();
        }

        private void PresenterUnchecked(object sender, System.Windows.RoutedEventArgs e) {
            SavingIndicator.IsBusy = true;
            _ctx.RemoveUserRole(PRESENTER_ROLE, OperationComplete, null);
            WebContext.Current.Authentication.LoadUser();
        }

        private void OperationComplete(InvokeOperation op) {
            //TODO: Check here if there was an error
            SavingIndicator.IsBusy = false;

        }

    }
}